<template>
<<<<<<< HEAD
  <div class="category-management" id="GoodKinds">
    <el-button type="primary" @click="showAddCategoryDialog()">添加类别</el-button>
    <el-tree
  :data="categories"
  :props="defaultProps"
  accordion
  class="category-tree"
  @node-click="handleNodeClick">
<template #default="{ node, data }">
        <div>
          <span>{{ node.label }}</span>
          <div class="operations">
            <el-button type="text" size="mini" @click="edit(data)">编辑</el-button>
            <el-button type="text" size="mini" @click="remove(node, data)">删除</el-button>
          </div>
        </div>
      </template>
</el-tree>
    <!-- <el-tree
=======
  <div id="account">
    <h3>商品类别</h3>
    <div>
      <el-select v-model="status" style="margin-left: 10px">
        <el-option>全部</el-option>
        <el-option :value="0" label="显示启用类别">显示启用类别</el-option>
        <el-option :value="1" label="显示禁用类别">显示禁用类别</el-option>
      </el-select>
      <el-button
        type="primary"
        style="margin-left: 10px"
        @click="searchPage(1, 5)"
        >查询</el-button
      >
      <div style="float: right">
        <el-button type="primary" @click="dialogFormVisible = true"
          >新增</el-button
        >
        <el-button type="" @click="allUpdateSta()">禁用</el-button>
        <el-button type="primary" @click="allstartSta()">启用</el-button>
        <el-button type="" @click="reFlush()">刷新</el-button>
      </div>
    </div>
    <hr style="margin-top: 10px" />
    <div class="account-content" style="margin-top: 10px">
      <div>
        <el-table
          :data="treeData"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
          border
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            prop="categoryname"
            label="类别"
            width="200"
          ></el-table-column>
          <el-table-column prop="status" label="状态" width="150">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#66b1ff"
                inactive-color="#c1c1c1"
                :active-value="0"
                :inactive-value="0"
                @change="updateSta(scope.row.status, scope.row.id)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row.id)"
                type="text"
                size="small"
                >删除</el-button
              >
              <el-button
                @click="updateType(scope.row.id)"
                type="text"
                size="small"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog
      width="400px"
      top="100px"
      title="新增商品类别"
      :visible.sync="dialogFormVisible"
    >
      <AddCustomerType />
      <div slot="footer" class="dialog-footer">
        <el-button @click="flush()">取 消</el-button>
        <el-button type="primary" @click="flush()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      width="400px"
      top="100px"
      title="修改商品类别"
      :visible.sync="chooseType"
    ></el-dialog>
    <div>
      <table>
        <tr>
          <td>上级分类</td>
          <td>
            <el-button @click="choose = true">请选择分类</el-button>
            <div v-show="choose">
              <el-tree
                ref="tree"
                :data="treeData"
                :props="defaultProps"
                node-key="id"
                show-checkbox
                check-strictly
                @check-change="handleCheckChange"
              >
              </el-tree>
            </div>
          </td>
        </tr>
        <br />
        <tr>
          <td>类别</td>
          <td><el-input v-model="type.categoryname"></el-input></td>
        </tr>
        <br />
        <tr>
          <td></td>
          <td>
            <el-button
              style="margin-left: 170px"
              type="primary"
              @click="update()"
              >修改</el-button
            >
          </td>
        </tr>
      </table>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="flush1()">取 消</el-button>
      <el-button type="primary" @click="flush1()">确 定</el-button>
    </div>
    <div class="category-management" id="GoodKinds">
      <el-button type="primary" @click="showAddCategoryDialog()"
        >添加类别</el-button
      >
      <el-tree
        :data="categories"
        :props="defaultProps"
        accordion
        class="category-tree"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <div>
            <span>{{ node.label }}</span>
            <div class="operations">
              <el-button type="text" size="mini" @click="edit(data)"
                >编辑</el-button
              >
              <el-button type="text" size="mini" @click="remove(node, data)"
                >删除</el-button
              >
            </div>
          </div>
        </template>
      </el-tree>
      <!-- <el-tree
>>>>>>> 6be95d2b3200ab6fbb17d1e0a5a9b367f780cc8e
      :data="categories"
      node-key="id"
      :props="defaultProps"
      default-expand-all
      :expand-on-click-node="false"
      class="category-tree"
    >
      <template #default="{ node, data }">
        <div>
          <span>{{ node.label }}</span>
          <div class="operations">
            <el-button type="text" size="mini" @click="edit(data)">编辑</el-button>
            <el-button type="text" size="mini" @click="remove(node, data)">删除</el-button>
          </div>
        </div>
      </template>
    </el-tree> -->

<<<<<<< HEAD
    <!-- 添加/编辑商品类别对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="categoryForm">
        <el-form-item label="上级分类" :label-width="formLabelWidth">
          <el-cascader
            v-model="selectedParentIds"
            :options="categories"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            placeholder="请选择上级分类"
            clearable
            @change="handleParentChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="类别名称" :label-width="formLabelWidth">
          <el-input v-model="categoryForm.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCategory">确定</el-button>
      </span>
    </el-dialog>
=======
      <!-- 添加/编辑商品类别对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
        <el-form :model="categoryForm">
          <el-form-item label="上级分类" :label-width="formLabelWidth">
            <el-cascader
              v-model="selectedParentIds"
              :options="categories"
              :props="{ checkStrictly: true, value: 'id', label: 'name' }"
              placeholder="请选择上级分类"
              clearable
              @change="handleParentChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="类别名称" :label-width="formLabelWidth">
            <el-input v-model="categoryForm.name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCategory">确定</el-button>
        </span>
      </el-dialog>
    </div>
>>>>>>> 6be95d2b3200ab6fbb17d1e0a5a9b367f780cc8e
  </div>
</template>

<script>
<<<<<<< HEAD
export default {
  name: 'GoodKinds',
  data() {
    return {
      categories: [
        {
          id: 1,
          name: '食品',
          children: [
            {
              id: 2,
              name: '饮料',
              children: [
                { id: 3, name: '矿泉水' },
                { id: 4, name: '果汁' }
              ]
            },
            { id: 5, name: '零食' }
          ]
        },
        { id: 6, name: '日用品' ,children:[]}
      ],
      dialogVisible: false,
      dialogTitle: '添加类别',
      categoryForm: {
        id: '',
        name: '',
        parentIds: []
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      formLabelWidth: '120px',
      selectedParentIds: []
    };
  },
  methods: {
    showAddCategoryDialog() {
      this.dialogTitle = '添加类别';
      this.resetCategoryForm();
      this.dialogVisible = true;
    },
    append(data) {
      this.dialogTitle = '添加子类别';
      this.selectedParentIds = [data.id];
      this.categoryForm.parentIds = [data.id];
      this.categoryForm.name = '';
      this.dialogVisible = true;
    },
    edit(data) {
      this.dialogTitle = '编辑类别';
      this.categoryForm.id = data.id;
      this.categoryForm.name = data.name;
      this.selectedParentIds = data.parentIds;
      this.dialogVisible = true;
    },
    remove(node, data) {
      this.$confirm('确认删除该类别吗？').then(() => {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      }).catch(() => {});
    },
    handleParentChange(value) {
      this.categoryForm.parentIds = value;
    },
    resetCategoryForm() {
      this.categoryForm = {
        id: '',
        name: '',
        parentIds: []
      };
      this.selectedParentIds = [];
    },
    submitCategory() {
      if (this.dialogTitle === '添加类别') {
        const newCategory = {
          id: this.categories.length + 1,
          name: this.categoryForm.name,
          children: []
        };
        if (this.categoryForm.parentIds.length) {
          const parent = this.findCategoryById(this.categories, this.categoryForm.parentIds[0]);
          if (parent) {
            parent.children.push(newCategory);
          }
        } else {
          this.categories.push(newCategory);
        }
      } else {
        const index = this.categories.findIndex(c => c.id === this.categoryForm.id);
        if (index !== -1) {
          this.categories[index].name = this.categoryForm.name;
        }
      }
      this.dialogVisible = false;
    },
    findCategoryById(categories, id) {
      for (let i = 0; i < categories.length; i++) {
        if (categories[i].id === id) {
          return categories[i];
        } else if (categories[i].children) {
          const found = this.findCategoryById(categories[i].children, id);
          if (found) return found;
        }
      }
      return null;
    }
  }
=======
import AddCustomerType from "./AddCustomerType.vue";

export default {
  name: "Account",
  components: {
    AddCustomerType,
  },
  data() {
    return {
      pageInfo: "",
      treeData: [],
      dialogFormVisible: false,
      status: "",
      selectedids: [],
      chooseType: false,
      id: 0,
      categoryname: "",
      choose: false,
      selectedid: 0,
      defaultProps: {
        children: "children",
        label: "categoryname",
      },
      type: {
        id: "",
        categoryname: "",
        parentid: "",
      },
    };
  },
  methods: {
    handleClick: function (id) {
      this.axios({
        url: "/info/type/delete",
        params: {
          id: id,
        },
      }).then((rs) => {
        console.log(rs);
        if (rs.data.info === "success") {
          this.searchPage();
        } else {
          alert("该用户下有子类，无法删除");
        }
      });
    },
    updateType: function (id) {
      this.id = id;
      // alert(id)
      this.chooseType = true;
      this.axios({
        url: "/erp/goods/category/getCategory",
        params: {
          id: id,
        },
      }).then((rs) => {
        this.type = rs.data.category;
        console.log("myType", this.type);
      });
    },
    update: function () {
      if (this.type.categoryname === "") {
        alert("类别不能为空");
        return;
      }
      if (this.selectedid === null) {
        this.selectedid = 0;
      }
      const category = {
        id: this.id,
        parentid: this.selectedid,
        categoryname: this.type.categoryname,
      };
      console.log(category);
      this.axios({
        url: "/erp/goods/category/update",
        method: "POST",
        data: {
          ...category,
        },
      }).then((rs) => {
        if (rs.data.code === 200) {
          this.searchPage();
          this.dialogFormVisible = false;
          alert("修改成功");
        } else {
          alert("类别已存在");
        }
      });
    },
    handleCheckChange(node, checked) {
      // 如果取消勾选，则不进行操作
      if (checked) {
        // 取消勾选其他所有节点
        const allCheckedNodes = this.$refs.tree.getCheckedNodes();
        allCheckedNodes.forEach((checkedNode) => {
          if (checkedNode.id !== node.id) {
            this.$refs.tree.setChecked(checkedNode, false);
          }
        });
        // 设置当前勾选节点的 id
        this.selectedid = node.id;
        console.log(this.selectedid);
      } else {
        // 如果节点被取消勾选，重置 selectedid
        this.selectedid = null;
      }
    },
    // 用于初始化或重置 selectedid
    resetChecked() {
      this.selectedid = null;
      this.$refs.tree.setCheckedKeys([]);
    },
    reFlush: function () {
      window.location.reload();
    },
    allstartSta: function () {
      if (!Array.isArray(this.selectedids) || this.selectedids.length === 0) {
        return;
      }
      const formData = new FormData();
      formData.append("list", JSON.stringify(this.selectedids));
      this.axios
        .post(
          "/info/type/allStartSta",

          formData
        )
        .then((rs) => {
          this.searchPage();
          this.selectedids = [];
        });
    },
    allUpdateSta: function () {
      if (!Array.isArray(this.selectedids) || this.selectedids.length === 0) {
        return;
      }
      const formData = new FormData();
      formData.append("list", JSON.stringify(this.selectedids));
      this.axios.post("/info/type/allUpdateSta", formData).then((rs) => {
        this.searchPage();
        this.selectedids = [];
      });
    },
    handleSelectionChange(val) {
      // val 是一个数组，包含了所有选中行的数据对象
      this.selectedids = val.map((item) => item.id);
      console.log(this.selectedids);
    },
    updateSta: function (status, id) {
      // alert(status);
      const category = {
        status: status,
        id: id,
      };
      this.axios({
        url: "/erp/goods/category/update",
        method: "POST",
        data: {
          ...category,
        },
      }).then((rs) => {
        console.log(rs.data.result);
        this.searchPage();
      });
    },
    flush: function () {
      this.dialogFormVisible = false;
      this.searchPage();
    },
    flush1: function () {
      this.chooseType = false;
      this.searchPage();
    },
    buildTree(data) {
      const tree = [];
      const map = {};

      // 将所有节点添加到map中，方便后续查找
      data.forEach((item) => {
        map[item.id] = { ...item, children: [] };
      });

      // 构建树形结构
      data.forEach((item) => {
        if (item.parentid === 0) {
          tree.push(map[item.id]);
        } else {
          if (map[item.parentid]) {
            map[item.parentid].children.push(map[item.id]);
          }
        }
      });

      return tree;
    },
    searchPage: function () {
      this.axios({
        url: "/erp/goods/category/getList",
        params: {
          status: this.status,
        },
      }).then((rs) => {
        this.pageInfo = rs.data.list;
        console.log("list", rs.data.list);
        this.treeData = this.buildTree(this.pageInfo);
        console.log("myTreeData", this.treeData);
      });
    },
  },
  created: function () {
    this.searchPage();
    this.resetChecked();
  },
>>>>>>> 6be95d2b3200ab6fbb17d1e0a5a9b367f780cc8e
};
</script>

<style scoped>
<<<<<<< HEAD
=======
#account {
  width: 100%;
  height: 100%;
}

.account-top {
  width: calc(100% -20px);
  height: 60px;
  /* background-color: pink; */
  line-height: 60px;
  padding-left: 20px;
  font-size: 13px;
}

.account-top h3 {
  display: inline-block;
  margin-right: 1000px;
}

.account-content {
  width: 100%;
  height: calc(100% - 60px);
  /* background-color: skyblue; */
}

.el-input,
.el-button {
  font-size: 13px;
}
>>>>>>> 6be95d2b3200ab6fbb17d1e0a5a9b367f780cc8e
.category-management {
  padding: 20px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.category-tree {
  margin-top: 20px;
}

<<<<<<< HEAD
.el-tree-node__content{
    align-items: none;
=======
.el-tree-node__content {
  align-items: none;
>>>>>>> 6be95d2b3200ab6fbb17d1e0a5a9b367f780cc8e
}

.dialog-footer {
  text-align: right;
}

.operations {
<<<<<<< HEAD
 float: right;
margin-left: 40px;
margin-top: -2px;
=======
  float: right;
  margin-left: 40px;
  margin-top: -2px;
>>>>>>> 6be95d2b3200ab6fbb17d1e0a5a9b367f780cc8e
}
</style>